package com.siyoumi.app.modules.view_admin.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.entity.*;
import com.siyoumi.service.*;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/view_admin/view_admin__page__edit")
public class view_admin__page__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("页面管理-编辑");

        SysAppRouterService app = SysAppRouterService.getBean();

        Map<String, Object> data = new HashMap<>();
        data.put("appr_pid", "");
        data.put("appr_order", 0);
        data.put("appr_hidden", 0);
        if (isAdminEdit()) {
            SysAppRouter entity = app.loadEntity(getID());

            HashMap<String, Object> dataAppend = new HashMap<>();
            dataAppend.put("id", entity.getKey());

            //合并
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);

        //应用列表
        InputData inputData = InputData.getIns();
        inputData.put("pid", "all_1");
        QueryWrapper<SysAppRouter> query = app.getListQuery(inputData);
        query.select("appr_id", "appr_meta_title");
        List<SysAppRouter> listApp = app.list(query);
        setPageInfo("list_app", listApp);

        return getR();
    }


    @Transactional
    @PostMapping("/save")
    public XReturn save(@Validated() SysAppRouter entity, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //
        SysApp entityApp = SysAppService.getBean().getEntity(entity.getAppr_app_id());
        if (entityApp == null) {
            result.addError(XValidator.getErr("appr_app_id", "APPID错误"));
        }
        XValidator.getResult(result);

        SysAppRouterService app = SysAppRouterService.getBean();
        InputData inputData = XHttpContext.InputAll();
        inputData.putAll(entity.toMap());

        return app.saveEntity(inputData, true, null);
    }
}
